import type {
  TableColumnProps,
  ProSaasTableExposeType,
  ColumnsSpanType
} from '~/components/ProSaasTable/typings'
import type { LoopSwitchEnumType } from '~/store/monitorManagement/loopMonitorBox/typings'
import type { LoopSwitchGroupModalFormValuesType } from '../../components/loopSwitchGroupComponents/typings'
import type { LoopSwitchGroupInfoDataItemType } from './typings'
import { defineComponent, ref, reactive, watch, nextTick, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  ElCard,
  ElLink,
  ElSpace,
  ElButton,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElMessage
} from 'element-plus'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import ChangeLoopGroupModal from '../../components/loopSwitchGroupComponents/ChangeLoopGroupModal'
import HistoryTaskModal from '../../components/loopSwitchGroupComponents/HistoryTaskModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent(function LoopSwitchGroupContent() {
  // const router = useRouter()
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const changeLoopGroupDetailRef = ref<LoopSwitchGroupModalFormValuesType>({})
  const activeRecordRef = ref<LoopSwitchGroupInfoDataItemType>()
  const formValues = reactive<LoopSwitchGroupInfoDataItemType>({})
  const userState = useVuexGetters('user', ['permission'])
  const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', [
    'activeLoopGroupId',
    'loopSwitchSelectList'
  ])

  // 按回车搜索列表
  const handleKeyDownEnterSearchList = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 根据变更查询列表数据
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 切换变更分组弹框
  const handleToggleChangeLoopGroupModal = (record?: LoopSwitchGroupInfoDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要变更的数据' })
      return
    }
    changeLoopGroupDetailRef.value =
      record || proSaasTableRef.value!.selecteds?.length === 1
        ? {
            groupId: record?.taskGroupId || proSaasTableRef.value!.selecteds[0]?.taskGroupId,
            taskGroupLoopIds: record?.id || proSaasTableRef.value!.selecteds[0]?.id
          }
        : {
            groupId: null,
            taskGroupLoopIds: proSaasTableRef.value!.selecteds?.map((item) => item.id)?.join(',')
          }
  }

  // 关闭变更分组弹框并搜索
  const handleCloseChangeLoopGroupModal = () => {
    changeLoopGroupDetailRef.value = {}
    proSaasTableRef.value!?.toSearch()
  }

  // 打开历史任务弹框
  const handleChangeHistoryTaskModal = (record?: LoopSwitchGroupInfoDataItemType) => {
    activeRecordRef.value = record
    if (!record) proSaasTableRef.value!?.toSearch()
  }

  // 跳转至历史任务页面
  // const handleJumpHistoryTaskPage = (record?: LoopSwitchGroupInfoDataItemType) => {
  //   router.push({
  //     name: 'history_task',
  //     params: {
  //       id: record?.id,
  //       menuCode: 'loop_switch_group'
  //     }
  //   })
  // }

  // 过滤table数据
  const handleFilterTableData = (
    filterData: LoopSwitchGroupInfoDataItemType[]
  ): LoopSwitchGroupInfoDataItemType[] => {
    const filterSettings: Record<string, ColumnsSpanType> = {}
    return filterData.map((item) => {
      if (item?.deviceId && !filterSettings[item?.deviceId]) {
        filterSettings[item?.deviceId] = {
          rowspan: 1,
          colspan: 1
        }
        return {
          ...item,
          filterSettings: filterSettings[item?.deviceId]
        }
      } else {
        if (filterSettings?.[item?.deviceId!]) filterSettings[item.deviceId!].rowspan!++
        return {
          ...item,
          filterSettings: {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    })
  }

  watch(
    () => loopSwitchGroupState?.activeLoopGroupId?.value,
    () => {
      nextTick(proSaasTableRef.value!?.toSearch)
    }
  )

  onMounted(() => {
    if (!loopSwitchGroupState.loopSwitchSelectList.value?.length) {
      store.dispatch('loopSwitchGroup/GetLoopSwitchSelectList')
    }
  })

  const columns: TableColumnProps<LoopSwitchGroupInfoDataItemType>[] = [
    {
      label: '回路监控箱',
      prop: 'deviceName',
      minWidth: 170,
      showOverflowTooltip: true
    },
    {
      label: '回路开关',
      prop: 'loopName',
      minWidth: 170,
      showOverflowTooltip: true
    },
    {
      label: '所属分组',
      prop: 'taskGroupName',
      minWidth: 170,
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      align: 'center',
      width: 270,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('monitor_task_taskgroup_move') && (
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-biangengfenzu1" />}
              onClick={() => handleToggleChangeLoopGroupModal(row)}
            >
              变更分组
            </ElLink>
          )}
          <ElLink
            type="primary"
            icon={<AliIcon type="icon-lishirenwu1" />}
            onClick={() => handleChangeHistoryTaskModal(row)}
          >
            历史任务
          </ElLink>
        </ElSpace>
      )
    }
  ]
  return () => (
    <ElCard class={[styles['loop-group-content'], 'covered-with-content']}>
      <ProSaasTable<LoopSwitchGroupInfoDataItemType>
        tableId="loopSwitchGroup"
        ref={proSaasTableRef}
        columns={columns}
        rowKey="id"
        hasSelection
        useGridLayout={false}
        filterTableDataMethod={handleFilterTableData}
        spanMethod={({ row, column }) =>
          column.property === 'deviceName' ? row.filterSettings! : { rowspan: 1, colspan: 1 }
        }
        dispatchType="loopSwitchGroup/GetMonitorGroupLoopList"
        searchParams={{
          taskGroupId: loopSwitchGroupState?.activeLoopGroupId?.value,
          loopName: formValues.loopName,
          deviceName: formValues.deviceName && handleTrim(formValues.deviceName)
        }}
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="loopName" prop="loopName">
            <ElSelect
              v-model={formValues.loopName}
              placeholder="请选择回路开关"
              clearable
              onChange={handleChangeValueActionSearchList}
            >
              {loopSwitchGroupState?.loopSwitchSelectList?.value?.map(
                (item: LoopSwitchEnumType) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictValue!} />
                )
              )}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="deviceName" prop="deviceName">
            <ElInput
              v-model={formValues.deviceName}
              placeholder="回路监控箱名称"
              clearable
              onKeydown={handleKeyDownEnterSearchList}
            />
          </ElFormItem>
        ]}
      >
        {userState.permission.value.has('monitor_task_taskgroup_move') && (
          <ElButton
            type="primary"
            // icon={<AliIcon type="icon-daochu" />}
            onClick={() => handleToggleChangeLoopGroupModal()}
          >
            批量变更分组
          </ElButton>
        )}
      </ProSaasTable>
      {changeLoopGroupDetailRef.value.taskGroupLoopIds && (
        <ChangeLoopGroupModal
          visible={!!changeLoopGroupDetailRef.value?.taskGroupLoopIds}
          detail={changeLoopGroupDetailRef.value}
          cancel={handleCloseChangeLoopGroupModal}
        />
      )}
      {activeRecordRef.value && (
        <HistoryTaskModal
          visible={!!activeRecordRef.value}
          detail={activeRecordRef.value}
          cancel={() => handleChangeHistoryTaskModal()}
        />
      )}
    </ElCard>
  )
})
